package com.uinnova.beetlstu.web;

import com.uinnova.beetlstu.model.Blog;
import com.uinnova.beetlstu.model.User;
import com.uinnova.beetlstu.service.BlogService;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
/*
 *@author 王刚
 *@date 2019-01-19 14:14
 *
 */

@Controller
public class IndexController {
//
//    @Autowired
//    private BlogService blogService;
//    /*
//    *@GetMapping是requestMapping与method = get的结合
//    *user为null则返回login页面，校验通过到index.html
//    */

    @Autowired
    private BlogService blogService;

    //    进入登录页面
    @GetMapping(value = "/")
    public String preLogin() {
        return "login.html";
    }

    //    登录方法
    @GetMapping(value = "/beetl/login")
    public String login(@RequestParam(required = false) String userName, @RequestParam(required = false) String password, HttpServletRequest request) {
        /*
         *用户名或者密码为空，重新登录，用户名密码不为空在进行判断，返回用户不为null跳转到首页
         */
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return "redirect:/";
        }


        User user = blogService.login(userName, password);
        if (user == null) {
            return "redirect:/";
        }

        request.getSession().setAttribute("user", user);

        return "redirect:/index";
    }

    /*
     *@author 王刚
     *@date 2019-01-29 18:05
     *首页
     */
    @GetMapping("/index")
    public String index(@RequestParam(required = false, defaultValue = "1") Integer pageNumber,
                        @RequestParam(required = false, defaultValue = "8") Integer pageSize,
                        @RequestParam(required = false) String keyword,
                        @RequestParam(required = false) String category,
                        HttpServletRequest request) {
        PageQuery<Blog> pageQuery = blogService.pageBlog(pageNumber, pageSize, keyword, category);
        request.setAttribute("page", pageQuery);
        request.setAttribute("category", category);
        request.setAttribute("keyword", keyword);
        System.out.println("我就是keyword，我是：" + pageQuery);
        return "index.html";
    }

    /*
     *@author 王刚
     *@date 2019-01-29 18:05
     *详情评论页面，需要分页
     */
    @GetMapping(value = "/detail")
    public String detail(@RequestParam(required = false) Long id,@RequestParam(required = false,defaultValue = "1") Integer pageNumber, @RequestParam(required = false,defaultValue = "8") Integer pageSize, HttpServletRequest request) {

        request.setAttribute("blog",blogService.queryBlogById(id));
        request.setAttribute("message",blogService.pageMsg(id,pageNumber,pageSize));
        return "single.html";
    }





}
